package Classic150;

import java.util.ArrayList;
import java.util.List;

public class 组合总和 {

    int[] candidates;
    int target;
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> comb = new ArrayList<>();

    /*
        注意是组合，以及sum大于target时直接不进入回溯
     */
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        this.candidates = candidates;
        this.target = target;
        backTracking(0, 0);
        return res;
    }

    private void backTracking(int sum, int index) {
        if (sum == target) {
            res.add(new ArrayList<>(comb));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (sum + candidates[i] <= target) {
                comb.add(candidates[i]);
                backTracking(sum + candidates[i], i);
                comb.removeLast();
            }
        }
    }
}
